package com.yqg.protection.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yqg.protection.controller.dto.ImportVideoDeviceDto;
import com.yqg.protection.entity.VideoDevice;
import com.yqg.protection.listenern.VideoDeviceListener;
import com.yqg.protection.mapper.VideoDeviceMapper;
import com.yqg.protection.service.IVideoDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

/**
 * VideoDeviceServiceImpl 服务实现类
 * @author zxf
 * @since 2024-09-14
 */
@Service
@Slf4j
public class VideoDeviceServiceImpl extends ServiceImpl<VideoDeviceMapper, VideoDevice> implements IVideoDeviceService {

    @Resource
    private VideoDeviceMapper videoDeviceMapper;

    @Resource
    private VideoDeviceListener videoDeviceListener;

    @Override
    public void export(HttpServletResponse response, String clientName, String name, String deviceNum, String monitorNum, Integer level, Long organizationId, String isAllClient, List<Long> clientIds) {
        try {
            //设置下载
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = null;
            fileName = URLEncoder.encode("监控设备表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            //查询所有数据
            List<VideoDevice> exportData = videoDeviceMapper.exportData(clientName, name, deviceNum, monitorNum, level, organizationId, isAllClient, clientIds);
            //EasyExcel 写操作
            EasyExcel.write(response.getOutputStream(), VideoDevice.class)
                    .sheet("监控设备表")
                    .doWrite(exportData);
        } catch (Exception e) {
            log.info("exception ", e);
        }
    }

    @Override
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), ImportVideoDeviceDto.class, videoDeviceListener)
                    .sheet(0).headRowNumber(1).doRead();
        } catch (Exception e) {
            log.info("导入异常，请稍后重试！", e);
        }
    }
}
